package resultx

import (
	e "community-service/pkg/errorx"
	"community-service/pkg/errorx/pb"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
	"net/http"
)

func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {

	if err == nil {
		r := Success(resp)
		httpx.WriteJson(w, http.StatusOK, r)
	} else {
		//错误返回
		errcode := e.ServerCommonError
		errmsg := e.MapErrMsg(e.ServerCommonError)
		causeErr := errors.Cause(err)                      // err类型
		if gstatus, ok := status.FromError(causeErr); ok { // grpc err错误
			for _, v := range gstatus.Details() {
				detail := v.(*pb.Error)
				grpcCode := uint32(detail.Code)
				if e.IsCodeErr(grpcCode) { //区分自定义错误跟系统底层、db等错误，底层、db错误不能返回给前端
					errcode = grpcCode
					errmsg = detail.Msg
				}
			}
		}

		logx.WithContext(r.Context()).Errorf("[API-ERR]: %+v ", err)

		httpx.WriteJson(w, http.StatusOK, Error(errcode, errmsg))
	}
}
